package org.tea.inventory.utils;

import cn.hutool.extra.servlet.ServletUtil;
import io.netty.util.CharsetUtil;
import org.tea.inventory.base.contants.Constants;
import org.tea.inventory.base.exception.ApplicationException;
import org.tea.inventory.cache.constans.CacheConstants;
import org.tea.inventory.cache.utils.RedisUtil;
import org.tea.inventory.domain.sys.UserInfo;
import org.tea.inventory.service.IUserInfoService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author hanzy
 * @description
 * @date 2023年06月05日 13:25
 */
@Component
public class UserUtil {
    private static IUserInfoService userInfoService;
    @Resource
    private IUserInfoService iUserInfoService;

    public static UserInfo getUserInfo() {
        UserInfo userInfo = userInfoService.selectUserInfoByLognId(getUserId());
        if (userInfo == null) {
            throw new ApplicationException(503, "请登录");
        }
        return userInfo;
    }

    public static UserInfo getUser() {
        UserInfo userInfo = new UserInfo();
        HttpServletRequest request = getRequest();
        String authorization = ServletUtil.getHeader(request, Constants.AUTHORIZATION, CharsetUtil.UTF_8);
        if (authorization == null || authorization.isEmpty()) {
            return userInfo;
        }
        String key = CacheConstants.redisKey + authorization + ":";
        String loginId = String.valueOf(RedisUtil.get(key));
        if (!Objects.equals(loginId, "null")) {
            userInfo = userInfoService.selectUserInfoByLognId(getUserId());
        }

        return userInfo;
    }

    public static String getUserId() {
        HttpServletRequest request = getRequest();
        System.out.println("request:" + request);
        String authorization = ServletUtil.getHeader(request, Constants.AUTHORIZATION, CharsetUtil.UTF_8);
        System.out.println("authorization:" + authorization);
        if (authorization == null || authorization.isEmpty()) {
            throw new ApplicationException(503, "请登录");
        }
        String key = CacheConstants.redisKey + authorization + ":";
        String loginId = String.valueOf(RedisUtil.get(key));
        if (Objects.equals(loginId, "null")) {
            throw new ApplicationException(503, "请登录");
        }
        return loginId;
    }

    public synchronized static HttpServletRequest getRequest() {
        final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest();
    }

    @PostConstruct
    public void init() {
        userInfoService = iUserInfoService;
    }
}
